<?php

declare(strict_types=1);

namespace Hyperfx\Framework\Controller;

use Hyperf\Contract\ValidatorInterface;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Hyperfx\Framework\Exception\AppException;
use Hyperfx\Framework\Support\Response;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface as PsrResponseInterface;


abstract class AbstractController
{
    #[Inject]
    protected ContainerInterface $container;

    #[Inject]
    protected ValidatorFactoryInterface $validationFactory;

    /**
     * 响应成功信息.
     *
     * @param array $data
     * @return PsrResponseInterface
     */
    protected function success(ResponseInterface $response, array $data = [], string $msg = 'success', int $code = 200, array $extend = []): PsrResponseInterface
    {
        $json = Response::json($code, $msg, $data, $extend);

        return $response->json($json);
    }

    /**
     * 响应失败信息.
     *
     * @param array $data
     */
    protected function failed(string $msg = 'failed', array $data = [], int $code = 400, array $extend = [])
    {
        $exception =  new AppException($code, $msg, $data);
        $exception->setDebug(false);
        throw $exception;
    }

    public function validate(ValidatorInterface $validator,array $casts = []): array
    {
        if ($validator->fails()){
            $errorMessage = $validator->errors()->first();
            throw new AppException(400, $errorMessage);
        }
        $params = $validator->validated();
        if (!empty($casts)) {
            foreach ($casts as $key => $val) {
                if (isset($params[$key])) {
                    if (0 === strcmp($val, 'int')) {
                        $params[$key] = (int) $params[$key];
                    }
                }
            }
        }
        return $params;
    }
}